using Microsoft.Win32;
using System.Diagnostics;

namespace TightVNCTool
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            this.Text = this.Text + " V." + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            listView1.DoubleClick += ListView1_DoubleClick;
            var imagelist = new ImageList();
            imagelist.Images.Add(Properties.Resources.dianshizhibo);
            listView1.SmallImageList = imagelist;

            LoadJsonData();
        }

        private Vnc Vnc { get; set; } = new Vnc();

        private void LoadJsonData()
        {
            try
            {
                var text = File.ReadAllText("data.json");
                //VncHelp.Vnc = Newtonsoft.Json.JsonConvert.DeserializeObject<Vnc>(text, new VncJsonConverter()) ?? new Vnc();
                Vnc = System.Text.Json.JsonSerializer.Deserialize<Vnc>(text, SourceGenerationContext.Default.Options) ?? new Vnc();
            }
            catch (Exception)
            {
                Vnc = new Vnc();
            }
            VncToView();
        }

        private void ListView1_DoubleClick(object? sender, EventArgs e)
        {
            StartVncView();
        }

        private void ToolStripButton1_Click(object sender, EventArgs e)
        {
            var vncItem = new VncItem();
            Vnc.Items.Add(vncItem);
            EditVncItem(vncItem);
        }

        public void VncToView()
        {
            var vnc = Vnc;
            listView1.Items.Clear();
            foreach (var item in vnc.Items)
            {
                listView1.Items.Add(new ListViewItem([item.Description, item.Host, item._password], 0) { Tag = item });
            }
        }

        private void ToolStripButton3_Click(object sender, EventArgs e)
        {
            StartVncView();
        }


        class Options
        {
            /// <summary>
            /// 是否全屏
            /// </summary>
            public bool Fullscreen { get; set; }
            /// <summary>
            /// 缩放Auto
            /// </summary>
            public bool Fitwindow { get; set; }
            /// <summary>
            /// 缩放分母
            /// </summary>
            public int Scale_den { get; set; } = 1;
            /// <summary>
            /// 缩放分子
            /// </summary>
            public int Scale_num { get; set; } = 1;

            /// <summary>
            /// 缩放比例
            /// </summary>
            public double Scale => (double)Scale_num / Scale_den * 100;
        }

        private static Options GetOptions(string host)
        {
            using var registryKey = Registry.CurrentUser.OpenSubKey("Software\\TightVNC\\Viewer\\History\\" + host);

            var option = new Options();
            if (registryKey != null)
            {
                option.Fullscreen = registryKey.GetValue("Fullscreen")?.ToString() == "1";
                option.Scale_den = int.Parse(registryKey.GetValue("Scale_den")?.ToString() ?? "1");
                option.Scale_num = int.Parse(registryKey.GetValue("Scale_num")?.ToString() ?? "1");
                option.Fitwindow = registryKey.GetValue("Fitwindow")?.ToString() == "1";
            }
            return option;
        }

        private void StartVncView()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                this.Enabled = false;
                var item = listView1.SelectedItems[0];

                if (item.Tag is VncItem vncItem)
                {
                    var option = GetOptions(vncItem.Host);

                    string exePath = "tvnviewer.exe";
                    string arguments = $"-host=\"{vncItem.Host}\" -password=\"{vncItem._password}\" -scale={(option.Fitwindow ? "auto" : option.Scale)} -fullscreen={(option.Fullscreen ? "yes" : "no")}";
                    try
                    {
                        // 创建一个新的进程
                        var processStartInfo = new ProcessStartInfo("cmd", $"/c {exePath} {arguments}")
                        {
                            CreateNoWindow = true,
                            UseShellExecute = false,
                        };
                        // 启动进程
                        Process.Start(processStartInfo);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                this.Enabled = true;
            }
        }

        private void ToolStripButton2_Click(object sender, EventArgs e)
        {
            var vncItem = GetSelectVncItem();
            if (vncItem is null)
                return;
            EditVncItem(vncItem);
        }

        private void EditVncItem(VncItem vncItem)
        {
            var fm = new Form2(vncItem);
            fm.SaveClick = s =>
            {
                SaveJson();
                fm.Close();
                LoadJsonData();
            };
            fm.ShowDialog();
        }

        void SaveJson()
        {
            //var text = Newtonsoft.Json.JsonConvert.SerializeObject(VncHelp.Vnc, new VncJsonConverter());
            var text = System.Text.Json.JsonSerializer.Serialize(Vnc, SourceGenerationContext.Default.Options);
            File.WriteAllText("data.json", text);
        }

        private void ToolStripButton4_Click(object sender, EventArgs e)
        {
            var vncItem = GetSelectVncItem();
            if (vncItem is null)
                return;

            Vnc.Items.Remove(vncItem);
            SaveJson();
            LoadJsonData();
        }

        private VncItem? GetSelectVncItem()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                var item = listView1.SelectedItems[0];
                if (item.Tag is VncItem vncItem)
                {
                    return vncItem;
                }
            }
            return null;
        }
    }
}